package com.xzm.utils;

import lombok.Data;
import lombok.experimental.Accessors;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

@Data
@Accessors(chain = true)
public class NumberChainUtils {

    private BigDecimal value;

    private NumberChainUtils(Object value) {
        this.value = objectConvertBigDecimal(value);
    }

    public static NumberChainUtils getInstance(Object number) {
        return new NumberChainUtils(objectConvertBigDecimal(number));
    }

    /**
     * Object类型的数字转BigDecimal。https://blog.csdn.net/davis_23/article/details/81698208
     */
    public static BigDecimal objectConvertBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                // ret = new BigDecimal(((Number) value).doubleValue());
                ret = BigDecimal.valueOf(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
                        + " into a BigDecimal.");
            }
        }
        return ret;
    }

    public BigDecimal getValue() {
        return value;
    }

    public NumberChainUtils add(Object number2) {
        return setValue(value.add(objectConvertBigDecimal(number2)));
    }

    public NumberChainUtils subtract(Object number2) {
        return setValue(value.subtract(objectConvertBigDecimal(number2)));
    }

    public NumberChainUtils multiple(Object number2) {
        return setValue(value.multiply(objectConvertBigDecimal(number2)));
    }

    public NumberChainUtils divide(Object number2) {
        return setValue(value.divide(objectConvertBigDecimal(number2), 2, RoundingMode.HALF_UP));
    }

    public NumberChainUtils divide(Object number2, int scale) {
        return setValue(value.divide(objectConvertBigDecimal(number2), scale, RoundingMode.HALF_UP));
    }

    public NumberChainUtils divide(Object number2, int scale, RoundingMode roundingMode) {
        return setValue(value.divide(objectConvertBigDecimal(number2), scale, roundingMode));
    }

}
    